#!/bin/bash
# 作者：耗子 978107204@qq.com
# 时间：2021-3-12

# if ! [ $(id -u) = 0 ]; then
#   echo "需要安装软件 所以必须使用sudo运行该脚本！" 
#   exit 1
# fi
sudo apt-get -y install samba
echo -n "请输入需要共享的目录[/home/share]（不存在则会自动创建）："
read -r share_dir
if [ -z "$share_dir" ]; then
    share_dir="/home/share"
    echo "没有输入，建立默认共享文件夹/home/share"
fi
echo -n "请输入共享的名称[share]（别名）："
read -r share_name
if [ -z "$share_name" ]; then
    share_name="share"
fi
sudo mkdir -p "${share_dir}"
sudo chmod -R 777 "${share_dir}"
echo -n "请输入可以登陆samba的账号名（不填写则会使用root）："
read -r user_name
if [ -n "$user_name" ]; then
    echo "请设置共享的${user_name}密码"
    sudo smbpasswd -a "${user_name}"
else
    echo "请设置共享的root密码"
    user_name="root"
    smbpasswd -a root
fi

# 添加共享目录
# sudo cat <<EOF >> /etc/samba/smb.conf
sudo bash -c "cat > /etc/samba/smb.conf" <<EOF
[global]
    wide links = yes
    follow symlinks = yes
    unix extensions = no
[${share_name}]
   comment = ${share_name}
   path = ${share_dir}
   create mask = 0755
   directory mask = 0755
   valid users = ${user_name}
   browseable = yes
   writeable = yes
   guest ok = yes
   read only = no
   public = yes
   available = yes
EOF

# 重启samba
sudo systemctl restart smbd
# 设置samba开机自启动
sudo systemctl enable smbd

ips=`ifconfig -a|grep inet|grep -v 127.0.0.1|grep -v inet6|awk '{print $2}'|tr -d "addr:"​`
ip_num=`echo "${ips}" | wc -l`
if [ "${ip_num}" -gt 1 ]; then
    echo "本机有多个IP："
    echo "${ips}"
    browser_url="file://ip/${share_name}/"
    windows_url="\\\ip\\${share_name}"
    echo "浏览器通过\"${browser_url}\",windows通过\"${windows_url}\"访问"
else
    browser_url="file://${ips}/${share_name}/"
    windows_url="\\\${ips}\\${share_name}"
    echo "浏览器通过\"${browser_url}\",windows通过\"${windows_url}\"访问"
fi

exit
